<template>
  <n-drawer
    v-model:show="show"
    placement="right"
    min-w-500
    display-directive="if"
    resizable
  >
    <n-drawer-content
      :title="pageType === 'add' ? '添加角色' : '修改角色'"
      closable
    >
      <n-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-placement="left"
        :label-width="100"
      >
        <n-form-item label="名称" path="name">
          <n-input placeholder="请输入角色名称" v-model:value="formData.name" />
        </n-form-item>
        <n-form-item label="标识" path="code">
          <n-input placeholder="请输入角色标识" v-model:value="formData.code" />
        </n-form-item>
        <n-form-item label="状态" path="status">
          <n-switch v-model:value="formData.status">
            <template #checked>启用</template>
            <template #unchecked>禁用</template>
          </n-switch>
        </n-form-item>
        <n-form-item label="描述" path="remark">
          <n-input
            type="textarea"
            placeholder="请输入角色描述"
            v-model:value="formData.remark"
          />
        </n-form-item>
      </n-form>

      <template #footer>
        <n-space>
          <n-button type="primary" :loading="loading" @click="handleSubmit">
            提交
          </n-button>
          <n-button @click="handleReset">重置</n-button>
          <n-button @click="show = false">取消</n-button>
        </n-space>
      </template>
    </n-drawer-content>
  </n-drawer>
</template>

<script lang="ts" setup>
import { cloneDeep } from "@/utils";
import { FormInst } from "naive-ui";
import { roleApi } from "@/api";
import { Props, Emits, formRules } from "./common";
import { useLoadingFunc } from "@/hooks";

const props = withDefaults(defineProps<Props>(), {
  data: () => ({
    name: "",
    code: "",
    status: true,
    remark: "",
  }),
});
const emits = defineEmits<Emits>();

const formRef = ref<FormInst>();
const show = ref(false);
const formData = ref(cloneDeep(props.data));

watch(
  () => props.data,
  (newV) => (formData.value = cloneDeep(newV)),
  { deep: true }
);

const { loading, func: handleSubmit } = useLoadingFunc(async () => {
  await formRef.value?.validate();
  if (props.pageType === "add") {
    await roleApi.add(formData.value);
    window.$message?.success("添加成功");
  } else {
    await roleApi.update(formData.value);
    window.$message?.success("修改成功");
  }
  show.value = false;
  emits("submitSuccess");
  handleReset();
});

const handleReset = () => {
  formRef.value?.restoreValidation();
  formData.value = cloneDeep(props.data);
};

const funShow = () => (show.value = true);
defineExpose({ show: funShow });
</script>
